﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using AgileNYCWebService.Manager.Data;
using Newtonsoft.Json;

namespace AgileNYCWebService
{
	/// <summary>
	/// Summary description for photo
	/// </summary>
	public class photo : IHttpHandler
	{

		public void ProcessRequest(HttpContext context)
		{
			int userCode = int.Parse(context.Request.QueryString["Code"]);
			if (userCode > 999 && userCode < 10000)
			{
				object photoData = new DataManager().GetPhotoBytes(userCode);

				if (photoData != null && photoData.GetType() == typeof(byte[]))
				{
					byte[] photo = (byte[])photoData;

					using (MemoryStream mem = new MemoryStream(photo, 0, photo.Length))
					{
						mem.Write(photo, 0, photo.Length);
						mem.Seek(0, SeekOrigin.Begin);

						context.Response.ContentType = "image/png";

						mem.CopyTo(context.Response.OutputStream, Convert.ToInt32(photo.Length));
						context.Response.Flush();
					}
				}
				else
				{
					if (!string.IsNullOrEmpty(photoData.ToString()))
					{
						context.Response.Write("{ImageUrl:" + photoData + "}");
					}
					else
					{
						context.Response.Write(null);
					}
					context.Response.ContentType = "application/json";
					context.Response.Charset = "utf-8";
					context.Response.Flush();
				}
			}
			else
			{
				context.Response.ContentType = "application/json";
				context.Response.Charset = "utf-8";
				context.Response.Write("{Error: \"Invalid code\"}");
				context.Response.Flush();
			}
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}